package com.icarsaas.saas.tenant.system.model;

import com.icarsaas.saas.common.utils.HttpServletUtil;
import com.icarsaas.saas.component.base.DataEntity;
import lombok.Data;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.*;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.util.StringUtils;

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.*;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * 文件上传
 * 
 * @author chlingm
 *
 */
@EntityListeners(AuditingEntityListener.class)
@Data @Entity @Table(name = "sys_file_upload")
@DynamicInsert @DynamicUpdate
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@org.hibernate.annotations.Table(appliesTo = "sys_file_upload",comment="附件表")
public class FileUpload extends DataEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(generator="system-uuid")
	@GenericGenerator(name="system-uuid", strategy = "org.hibernate.id.UUIDGenerator")
	@Column(name = "id", nullable = false, insertable = true, updatable = true, length = 36)
	private String id;
	/** 文件名 */
	@Column(columnDefinition="varchar(500) COMMENT '附件名称'")
	private String name;
	/** 附件物理名称 */
	@Column(columnDefinition="varchar(500) COMMENT '附件物理名称'")
	private String phyName;
	@Column(columnDefinition="varchar(50) COMMENT '附件类别'")
	private String type;
	/** 文件路径 */
	@Column(columnDefinition="varchar(255) COMMENT '文件路径'")
	private String path;
	/** 文件类型 */
	@Column(columnDefinition="varchar(50) COMMENT '文件类型'")
	private String mime;
	/** 文件大小 */
	@Column(columnDefinition="bigint COMMENT '文件大小'")
	private Long size;
	@Column(columnDefinition="varchar(256) COMMENT '文件关联id'")
	private String refId;

	/**
	 * 获取文件绝对路径
 	 */
	public String getUrl() {
		HttpServletRequest request = HttpServletUtil.getRequest();
		if (!StringUtils.isEmpty(path)) {
			StringBuffer url = request.getRequestURL();
			String baseUrl = url.delete(url.length() - request.getRequestURI().length(), url.length())
					.append(request.getContextPath()).toString();
			return baseUrl + path;
		}
		return path;
	}
}
